package com.shenmazong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenmazong.mapper.TbSellerMapper;
import com.shenmazong.pojo.TbAdmin;
import com.shenmazong.pojo.TbSeller;
import com.shenmazong.service.TbAdminService;
import com.shenmazong.mapper.TbAdminMapper;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.utils.TokenUtils;
import com.shenmazong.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
@Slf4j
public class TbAdminServiceImpl extends ServiceImpl<TbAdminMapper, TbAdmin>
    implements TbAdminService{

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    TbAdminMapper tbAdminMapper;

    @Autowired
    TbSellerMapper tbSellerMapper;

    @Override
    public ResultResponse userLogin(LoginVo loginVo) {
        //-- 判断用户存不存在
        TbAdmin tbAdmin = tbAdminMapper.selectOne(
                new QueryWrapper<TbAdmin>().lambda().eq(TbAdmin::getAdminName, loginVo.getUserName()).last("limit 1")
        );
        if(tbAdmin == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        //-- 判断密码
        if(!tbAdmin.getAdminPass().equals(loginVo.getPassWord())) {
            return ResultResponse.FAILED(403, "密码不正确");
        }

        //-- 生成token

        // token过期时间：redis的过期时间
        // 注意：token的过期时间建议比redis中要稍微长一点
        String tokenKey = TokenUtils.token()
                .setKey("123456")
                .setExpire(60 * 30)
                .createToken("userId", ""+tbAdmin.getAdminId(), "userName", tbAdmin.getAdminName());

        //-- 把token放到redis
        // 问题1：token的key怎么设置：userId作为key：多终端的时候，是有问题：
        // key(seller:userid)=tokenKey(tokenKey)
        // tokenKey = realtoken

        // 问题2：token自动更新
        String realToken = tokenKey;
        String key = "admin:"+tbAdmin.getAdminId();
        redisTemplate.opsForValue().set(key, tokenKey, 30, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(tokenKey, realToken, 30, TimeUnit.MINUTES);

        //-- 返回用户信息
        AdminInfoVo adminInfoVo = new AdminInfoVo();
        BeanUtils.copyProperties(tbAdmin, adminInfoVo);
        adminInfoVo.setToken(tokenKey);

        return ResultResponse.SUCCESS(adminInfoVo);
    }

    @Override
    public ResultResponse userResetPassword(ResetPassworVo resetPassworVo) {
        // 获取用户
        TbAdmin tbAdmin = tbAdminMapper.selectById(resetPassworVo.getUserId());
        if(tbAdmin == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        // 比较密码
        if(!tbAdmin.getAdminPass().equals(resetPassworVo.getOldPass())) {
            return ResultResponse.FAILED(403, "密码不正确");
        }

        // 修改密码
        tbAdmin.setAdminPass(resetPassworVo.getNewPass());
        tbAdminMapper.updateById(tbAdmin);

        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse sendCode(MobileVo mobileVo) {
        // 生成随机验证码
        String code = "1234";

        // 验证码存入redis
        redisTemplate.opsForValue().set(mobileVo.getMobile(), code, 1, TimeUnit.MINUTES);

        // 调用短信发送接口
        log.info("code:"+code);

        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse addUser(AddAdminVo addAdminVo) {
        // 判断用户名是否存在(判断手机号)
        TbAdmin tbAdmin = tbAdminMapper.selectOne(new QueryWrapper<TbAdmin>().lambda().eq(TbAdmin::getAdminName, addAdminVo.getAdminName()));
        if(tbAdmin != null) {
            return ResultResponse.FAILED(410, "商家已存在");
        }

        // 开始注册
        TbAdmin admin = new TbAdmin();
        BeanUtils.copyProperties(addAdminVo, admin);

        tbAdminMapper.insert(admin);

        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse getSellerByPage(PageVo pageVo) {

        Page<TbSeller> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
        QueryWrapper<TbSeller> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(TbSeller::getSellerId);

        Page<TbSeller> tbSellerPage = tbSellerMapper.selectPage(page, queryWrapper);
        List<TbSeller> records = tbSellerPage.getRecords();
        ArrayList<SellerInfoVo> sellerInfoVos = new ArrayList<>();
        records.forEach(item->{
            SellerInfoVo sellerInfoVo = new SellerInfoVo();
            BeanUtils.copyProperties(item, sellerInfoVo);
            sellerInfoVos.add(sellerInfoVo);
        });

        //
        Page<SellerInfoVo> sellerInfoVoPage = new Page<>();
        BeanUtils.copyProperties(tbSellerPage, sellerInfoVoPage);
        sellerInfoVoPage.setRecords(sellerInfoVos);

        return ResultResponse.SUCCESS(sellerInfoVoPage);
    }
}




